package com.perceptivesoftware.licensing.server.handler;

import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.perceptivesoftware.licensing.server.util.PropertiesUtil;

public class PropertiesHandler
{
	final static Logger logger = Logger.getLogger(PropertiesHandler.class);
	
	public String getPropertiesFileName()
	{
		return PropertiesUtil.getProjectName().substring(1).toLowerCase().concat(".properties");
	}
	
	public String getProperty(final String prop)
	{
		final Properties properties = getProperties(getPropertiesFileName());
		if (properties == null)
		{
			return null;
		}
		else
		{
			return properties.getProperty(prop);
		}
	}

	public String getProperty(final String prop, final String strDefault)
	{
		final Properties properties = getProperties(getPropertiesFileName());
		if (properties == null)
		{
			return null;
		}
		else
		{
			return properties.getProperty(prop, strDefault);
		}
	}
	
	public Properties getProperties()
	{
		return getProperties(getPropertiesFileName());
	}
	
	public Properties getProperties(final String name)
	{
		Properties properties = new Properties();
		InputStream in = null;
		try
		{
			in = this.getClass().getClassLoader().getResourceAsStream(name);
			if (in != null)
			{
				properties.load(in); // Can throw IOException
			}
		}
		catch (final Exception e)
		{
			properties = null;
			logger.error("Error while loading properties from " + name);
		}
		finally
		{
			if (in != null)
			{
				try
				{
					in.close();
				}
				catch (final Throwable ignore)
				{
					logger.error("Error closing inputstream while loading " + name);
				}
			}
		}
		return properties;
	}
}